package com.wangp.mywrite.inwork.trans;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author: wp
 * @date: 2023/5/30 18:04:59
 * @desc:
 **/
public class TransientDemo {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("D:/user.txt");

        User user = new User();
        user.setId(1);
        user.setUsername("stronger");
        System.out.println("read before Serializable: ");
        System.out.println("id: " + user.getId());
        System.out.println("username: " + user.getUsername());
        try {
            ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(path));
            // 将User对象写进文件
            os.writeObject(user);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            ObjectInputStream is = new ObjectInputStream(Files.newInputStream(path));

            user = (User) is.readObject();
            is.close();

            System.out.println("\nread after Serializable: ");
            System.out.println("id: " + user.getId());
            System.out.println("username: " + user.getUsername());

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
